package gold.contest;

import gold.utils.InputUtil;
import gold.vo.TreeNode;

import java.util.HashMap;
import java.util.*;

/**
 * Created by fanzhenyu02 on 2021/12/10.
 * common problem solver template.
 */
public class LC6018 {
    public long startExecuteTime = System.currentTimeMillis();


    class Solution {
        public TreeNode createBinaryTree(int[][] descriptions) {
            Map<Integer, TreeNode> map = new HashMap<>();
            Set<Integer> rootCandidate = new HashSet<>();
            Set<Integer> childCandidate = new HashSet<>();

            for (int[] description : descriptions) {
                int pVal = description[0], cVal = description[1];
                if (!map.containsKey(pVal)) map.put(pVal, new TreeNode(pVal));
                if (!map.containsKey(cVal)) map.put(cVal, new TreeNode(cVal));
                if (description[2] == 1) map.get(pVal).left = map.get(cVal);
                else map.get(pVal).right = map.get(cVal);

                rootCandidate.add(pVal);
                if (rootCandidate.contains(cVal)) rootCandidate.remove(cVal);
                childCandidate.add(cVal);
            }

            for (Integer cVal : childCandidate) {
                if (rootCandidate.contains(cVal)) rootCandidate.remove(cVal);
            }

            int rooVal = rootCandidate.iterator().next();
            return map.get(rooVal);
        }
    }

    public void run() {
        Solution solution = new Solution();
        System.out.println(solution.createBinaryTree(InputUtil.toDoubleIntegerArray("[[20,15,1],[20,17,0],[50,20,1],[50,80,0],[80,19,1]]")));
        System.out.println(solution.createBinaryTree(InputUtil.toDoubleIntegerArray("[[1,2,1],[2,3,0],[3,4,1]]")));
    }

    public static void main(String[] args) throws Exception {
        LC6018 an = new LC6018();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
